package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstat;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.feign.ThirdPartFeignService;
import com.atguigu.common.vo.UserLoginVo;
import com.atguigu.gulimall.auth.vo.UserRegistVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {

    @Autowired
    ThirdPartFeignService thirdPartFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    MemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone){
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstat.SMS_CODE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)){
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 60*1000){
                //60秒内不能再发
                return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(),BizCodeEnume.VAILD_EXCEPTION.getMsg());
            }
        }

        //纺织刷新

        //key是手机号 value是值 sms:code: 13207141600  key    -> 42422 value
        String code = UUID.randomUUID().toString().substring(0,5);
        String substring =code+"_"+System.currentTimeMillis();
        redisTemplate.opsForValue().set(AuthServerConstat.SMS_CODE_PREFIX+phone,substring,10, TimeUnit.MINUTES);


        thirdPartFeignService.sendCode(phone,code);
        return R.ok();
    }

    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo vo, BindingResult result, Model model
    , RedirectAttributes redirectAttributes){
        if (result.hasErrors()){
            Map<String, String> collect = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField,
                    FieldError::getDefaultMessage));
//            model.addAttribute("errors",collect);
            redirectAttributes.addFlashAttribute("errors",collect);
            //校验出错，转发到注册页
            return "redirect:http://auth.gulimall.com/reg.html";
        }
//        真正注册 调用远程服务

        //校验验证码
        String code = vo.getCode();
        String s = redisTemplate.opsForValue().get(AuthServerConstat.SMS_CODE_PREFIX + vo.getPhone());
        if (!StringUtils.isEmpty(s)) {
            if (code.equals(s.split("_")[0])) {
                //删除验证码
                redisTemplate.delete(AuthServerConstat.SMS_CODE_PREFIX + vo.getPhone());
                //验证码通过
                R regist = memberFeignService.regist(vo);
                if (regist.getCode()==0){
                    //成功
                    return "redirect:http://auth.gulimall.com/login.html";
                }else {
                    Map<String, String> collect = new HashMap<>();
                    collect.put("msg",regist.getData("msg",new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("error",collect);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            } else {
                Map<String, String> collect = new HashMap<>();
                collect.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", collect);
                //校验出错，转发到注册页
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        }else {
            Map<String, String> collect = new HashMap<>();
            collect.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", collect);
            //校验出错，转发到注册页
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }


    @PostMapping("/login")
    public String login(UserLoginVo loginVo, RedirectAttributes redirectAttributes,
                        HttpSession session,
                        HttpServletResponse response){
        //表单接收的是Key values

        //Yuanc远程登录，重定向到首页 转json
        R r = memberFeignService.login(loginVo);
        if (r.getCode()==0){
            //成功
            MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {
            });
            session.setAttribute(AuthServerConstat.LOGIN_USER,data);
            return "redirect:http://gulimall.com";
        }else {
            //失败
            Map<String,String> errors = new HashMap<>();
            errors.put("msg",r.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
